﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BUSQLDV;
using DTOQLDV;
using System.Configuration;
using System.Threading;

namespace QLDV_DA
{
    public partial class frmMain : Form
    {

        #region Khai báo biến tham số
        private List<DTODuLieu> _dsDuLieuDuocChon;
        private List<String> _dsFil;     
        #endregion
        public frmMain()
        {
            InitializeComponent();          
            _dsFil = new List<string>();
            _dsDuLieuDuocChon = new List<DTODuLieu>();
        }   
        #region Xử lí cài đặt dữ liệu
        
        private void KhoiTao()
        {
            thKeyword.Properties.NullText = "<Xin nhập từ khóa>";
            thDanhSachBoLocHienCo.Properties.NullText = "<Xin chọn bộ lọc>";

            //Load tham số cho các cột dữ liệu
            rclMaDiaDiem.DataSource = SESSION._dsDiaDiem;
            rclMaDiaDiem.DisplayMember = "TenDiaDiem";
            rclMaDiaDiem.ValueMember = "MaDiaDiem";

            rclMaDichVu.DataSource = SESSION._dsDichVu;
            rclMaDichVu.DisplayMember = "TenDichVu";
            rclMaDichVu.ValueMember = "MaDichVu";

            rclMaDuong.DataSource = SESSION._dsDuong;
            rclMaDuong.DisplayMember = "TenDuong";
            rclMaDuong.ValueMember = "MaDuong";

            rclMaPhuong.DataSource = SESSION._dsPhuong;
            rclMaPhuong.DisplayMember = "TenPhuong";
            rclMaPhuong.ValueMember = "MaPhuong";

            rclMaQuanHuyen.DataSource = SESSION._dsQuanHuyen;
            rclMaQuanHuyen.DisplayMember = "TenQuanHuyen";
            rclMaQuanHuyen.ValueMember = "MaQuanHuyen";

            rclMaTinhThanh.DataSource = SESSION._dsTinhThanh;
            rclMaTinhThanh.DisplayMember = "TenTinhThanh";
            rclMaTinhThanh.ValueMember = "MaTinhThanh";
            //Load danh sách dữ liệu cho bản chính 
            thGridDanhSachDuLieu.DataSource = SESSION._dsDuLieu;
            //Tao cot check dau tien
            _selection = new GridCheckMarksSelection(thGridviewDanhSachDuLieu);
            _selection.CheckMarkColumn.VisibleIndex = 0;
        }        
       
        private void CapNhatBoLoc(String fil)
        {
            thGridviewDanhSachDuLieu.ActiveFilterString = fil;
            thDanhSachBoLocHienCo.SelectedIndex = -1;
            thKeyword.Focus();
        }

        private String TaoChuoiLoc()
        {
            String fil = "1=1 ";
            foreach (String s in _dsFil)
            {
                if (s != null && s != "")
                {
                    fil += " And " + s;
                }
            }
            return fil;
        }                 
        #endregion
        #region Các hàm xử lí sự kiện
        private void cnThemMoi_Click(object sender, EventArgs e)
        {
            try
            {

                frmThemMoi frmThemMoi = new frmThemMoi();
                frmThemMoi.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Xảy ra lỗi " + ex.Message, "Thông báo");
            }
            finally
            {
                LamTuoi();
            }
        }
        private void cnCapNhat_Click(object sender, EventArgs e)
        {
            if (_selection.SelectedCount > 0)
            {
                try
                {
                    List<DTODuLieu> dsDuLieuDuocChon = new List<DTODuLieu>();
                    for (int i = 0; i < _selection.SelectedCount; i++)
                    {
                        dsDuLieuDuocChon.Add((DTODuLieu)_selection.GetSelectedRow(i));
                    }
                    frmCapNhat frmCapNhat = new frmCapNhat(dsDuLieuDuocChon);
                    frmCapNhat.ShowDialog();                  
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Xảy ra lỗi " + ex.Message, "Thông báo");
                }
                finally
                {
                    _selection.ClearSelection();
                    LamTuoi();
                }
            }
            else
            {
                MessageBox.Show("Xin chọn dữ liệu cần chỉnh sửa", "Thông báo");
            }
        }
        private void frmMain_Load(object sender, EventArgs e)
        {
            try
            {
                frmsplash.ShowSplash();
                if (CaiDatThamSo())
                {
                    KhoiTao();                   
                }
                else
                {
                    MessageBox.Show("Xin kiểm tra lại kết nối", "Thông báo");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Xảy ra lỗi : '"+ex.Message+"'", "Thông báo");
            }
            finally
            {
                frmsplash.CloseSplash();
                this.Activate();
                this.WindowState = FormWindowState.Maximized;
            }
        }
        private void LamTuoi()
        {
            thGridDanhSachDuLieu.RefreshDataSource();
        }     
        private void cnXoa_Click(object sender, EventArgs e)
        {
            try
            {
                List<DTODuLieu> dsChon = new List<DTODuLieu>();
                DialogResult dl = MessageBox.Show("Bạn có muốn tiếp tục xóa các dòng dữ liệu này", "Thông báo", MessageBoxButtons.OKCancel);
                if (dl == DialogResult.OK)
                {
                    for (int i = 0; i < _selection.SelectedCount; i++)
                    {
                        DTODuLieu dtoDuLieu = (DTODuLieu)_selection.GetSelectedRow(i);
                        dsChon.Add(dtoDuLieu);
                        SESSION._dsDuLieu.Remove(dtoDuLieu);
                    }
                    BUSThread._dsDuLieu = dsChon;
                    BUSThread.ThucHienThreadXoaDuLieu();                    
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Xảy ra lỗi " + ex.Message, "Thông báo");
            }
            finally
            {
                _selection.ClearSelection();
                LamTuoi();                
            }
        }

        private void thTrangKe_Click(object sender, EventArgs e)
        {
            thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.DoClick(thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.NextPage);
        }

        private void thTrangCuoi_Click(object sender, EventArgs e)
        {
            thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.DoClick(thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.Last);
        }

        private void thTrangTruoc_Click(object sender, EventArgs e)
        {
            thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.DoClick(thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.PrevPage);
        }

        private void thTrangDau_Click(object sender, EventArgs e)
        {
            thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.DoClick(thGridDanhSachDuLieu.EmbeddedNavigator.Buttons.First);
        }        
        private void cnNhap_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog thChonFile = new OpenFileDialog();
                thChonFile.Filter = "Excel 2003|*.xls|Excel 2007/2010|*.xlsx|All|*.*";
                thChonFile.Title = "Chọn 1 file cần nhập";
                DialogResult dg = thChonFile.ShowDialog();
                if (dg == DialogResult.OK)
                {
                    String fileName = thChonFile.FileName;
                    frmNhapDuLieu frmNL = new frmNhapDuLieu(fileName);
                    frmNL.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Xảy ra lỗi '" + ex.Message + "'", "Thông báo");
            }
            finally
            {
                LamTuoi();
            }
        }
        private void cnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void thDanhSachBoLocDuocChon_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            if (thDanhSachBoLocDuocChon.Items[e.Index].CheckState == CheckState.Unchecked)
            {
                thDanhSachBoLocDuocChon.Items.RemoveAt(e.Index);
                _dsFil.RemoveAt(e.Index);
                CapNhatBoLoc(TaoChuoiLoc());
            }
        }
        private void cnXoaLoc_Click(object sender, EventArgs e)
        {
            _dsFil.Clear();
            thDanhSachBoLocDuocChon.Items.Clear();
            CapNhatBoLoc("1=1");
        }
        private void thDanhSachBoLocHienCo_Properties_SelectedIndexChanged(object sender, EventArgs e)
        {
            int i = thDanhSachBoLocHienCo.SelectedIndex;
            String kw = "";
            if (thKeyword.EditValue != null)
            {
                kw = thKeyword.EditValue.ToString().Trim();
            }
            if (i >= 0 && kw.Length > 0)
            {
                _dsFil.Add(" [" + thGridviewDanhSachDuLieu.Columns[i + 2].FieldName + "] Like '%" + kw + "%'");
                thDanhSachBoLocDuocChon.Items.Add(thDanhSachBoLocHienCo.SelectedItem + " = '" + kw + "'", true);
                thDanhSachBoLocHienCo.SelectedIndex = -1;
                thKeyword.EditValue = null;
                CapNhatBoLoc(TaoChuoiLoc());
            }
            else
            {
                thDanhSachBoLocHienCo.SelectedIndex = -1;
            }
        }       
        #endregion

        private void thGridviewDanhSachDuLieu_RowCountChanged(object sender, EventArgs e)
        {
            thTongSoDuLieu.Text = thGridviewDanhSachDuLieu.RowCount + "";
        }
        private bool CaiDatThamSo()
        {
            SESSION._cnnStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
            bool kq = BUSXuLi.KiemTraKetNoi();
            if (kq)
            {
                SESSION._dsDiaDiem = BUSDiaDiem.LayDanhSachDiaDiem();
                SESSION._dsDichVu = BUSDichVu.LayDanhSachDichVu();
                SESSION._dsDuLieu = BUSDuLieu.LayDanhSachDuLieu();
                SESSION._dsDuong = BUSDuong.LayDanhSachDuong();
                SESSION._dsPhuong = BUSPhuong.LayDanhSachPhuong();
                SESSION._dsQuanHuyen = BUSQuanHuyen.LayDanhSachQuanHuyen();
                SESSION._dsTinhThanh = BUSTinhThanh.LayDanhSachTinhThanh();                
            }            
            return kq;
        }

        private void cnThongTin_Click(object sender, EventArgs e)
        {
            frmThongTin frm = new frmThongTin();
            frm.ShowDialog();
        }

        private void thGridviewDanhSachDuLieu_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle > 0)
            {
                thDuLieuHienHanh.Text = e.FocusedRowHandle + "";
            }
            else
            {
                thDuLieuHienHanh.Text = "0";
            }
        }
    }
}
